﻿using FanaticRock.Core.Helpers;
using FanaticRock.DownloadManage.Helpers;
using System.Diagnostics.CodeAnalysis;

namespace FanaticRock.DownloadManage
{
    ///<summary>下载项</summary>
    public class IntervalDownloadItem : IDisposable
    {
        #region props

        public string Uri { get; private set; }

        public string LocalPath { get; private set; }

        public string TaskName { get; private set; }

        public double Progress { get; internal set; }

        public bool IsCompleted { get; internal set; } = false;

        #endregion

        #region cancel

        private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        #endregion

        #region ctors

        public IntervalDownloadItem([NotNull] string taskName, [NotNull] string uri, [NotNull] string localPath)
        {
            Uri = uri;
            TaskName = taskName;
            LocalPath = localPath;

            CancellationHelper.CreateCancellationTokenSource(ref _cancellationTokenSource);
        }

        #endregion

        #region methods

        internal async Task Download()
        {
            Progress = 0;
            CancellationHelper.CreateCancellationTokenSource(ref _cancellationTokenSource);
            await DownloadHelper.DownloadAsync(Uri, LocalPath, _cancellationTokenSource.Token);
        }

        internal void Cancel()
        {
            _cancellationTokenSource.Cancel();
        }

        public void Dispose()
        {
            CancellationHelper.DisposeCancellationTokenSource(ref _cancellationTokenSource);
        }

        #endregion

    }
}
